<template>
  <div class="login-container">
    <div class="login-box">
      <h3 class="login-title">VibeMusic-Admin 登录</h3>
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          label-width="80px"
          status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              :disabled="isLoading"
              clearable
              placeholder="请输入管理员用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              :disabled="isLoading"
              clearable
              placeholder="请输入管理员密码"
              show-password
              type="password"
          />
        </el-form-item>
        <!-- 新增验证码输入框和图片 -->
        <el-form-item label="验证码" prop="code">
          <div class="captcha-container">
            <el-input
                v-model="loginForm.code"
                :disabled="isLoading"
                class="captcha-input"
                clearable
                placeholder="请输入计算结果"
            />
            <div class="captcha-image-container">
              <img
                  :class="{ 'captcha-loading': isLoadingCaptcha }"
                  :src="captchaUrl"
                  alt="算术验证码"
                  class="captcha-image"
                  @click="refreshCaptcha"
                  @error="handleImageError"
              >
            </div>

          </div>
        </el-form-item>
        <el-form-item>
          <el-button
              :loading="isLoading"
              class="login-btn"
              type="primary"
              @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import http from '@/request/http.js'

const router = useRouter()
const route = useRoute()
const loginFormRef = ref(null)
const isLoading = ref(false)
const isLoadingCaptcha = ref(false)
const captchaUrl = ref('') // 验证码图片URL
console.log(captchaUrl)
// 初始化登录表单，添加code字段
const loginForm = reactive({
  username: '',
  password: '',
  code: '' // 验证码输入
})


// 表单验证规则，添加验证码验证
const loginRules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 20, message: '用户名长度在 2-20 个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 32, message: '密码长度在 6-32 个字符之间', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 1, message: '请输入正确的计算结果', trigger: 'blur'}
  ]
})

// 获取验证码图片
const getCaptcha = async () => {
  isLoadingCaptcha.value = true
  try {
    // 关键：设置响应类型为 Blob，避免 http 工具将二进制转成 JSON
    const response = await http.get(
        `/api/captcha/arithmetic?timestamp=${Date.now()}`,
        { responseType: 'blob' } // 必须加这行！
    )

    // 1. 释放之前的 Blob URL，避免内存泄漏
    if (captchaUrl.value) {
      URL.revokeObjectURL(captchaUrl.value)
    }

    // 2. 将 Blob 转成可被 img 识别的 Blob URL
    const blobUrl = URL.createObjectURL(response)
    captchaUrl.value = blobUrl

    await new Promise(resolve => setTimeout(resolve, 300))
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请重试')
  } finally {
    isLoadingCaptcha.value = false
  }
}


// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
  // 清空输入框
  loginForm.code = ''
}

// 页面加载时获取验证码
onMounted(() => {
  getCaptcha()
})

const handleLogin = async () => {
  // 表单校验
  const formValid = await loginFormRef.value.validate().catch(() => false)
  if (!formValid) return

  isLoading.value = true

  try {
    const response = await http.post('/api/admin/login', loginForm)

    if (response.code === 0 && response.data?.token) {
      // 存储Token
      sessionStorage.setItem('token', response.data.token)
      const username = response.data.username || loginForm.username
      sessionStorage.setItem('username', username)
      localStorage.setItem('isLogin', 'true')

      // 跳转页面
      const redirectPath = route.query.redirect || '/dashboard'
      router.push(redirectPath)

      ElMessage.success(response.msg || '登录成功，欢迎回来！')
    } else {
      // 登录失败时刷新验证码
      refreshCaptcha()
      ElMessage.error(response.msg || '登录失败，请检查账号密码或验证码')
    }
  } catch (error) {
    // 完善错误处理逻辑
    console.error('登录请求异常：', error)

    // 异常时刷新验证码
    refreshCaptcha()

    // 根据不同错误类型显示不同提示
    if (error.message.includes('ERR_CONNECTION_REFUSED')) {
      ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
    } else if (error.response) {
      // 有响应但状态码非200的情况
      ElMessage.error(error.response.data?.msg || `登录失败，状态码：${error.response.status}`)
    } else if (error.request) {
      // 有请求但无响应的情况
      ElMessage.error('服务器无响应，请稍后再试')
    } else {
      // 其他错误
      ElMessage.error('登录失败：' + error.message)
    }
  } finally {
    isLoading.value = false
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin: 0;
  padding: 0 20px;
}

.login-box {
  width: 100%;
  max-width: 420px;
  padding: 30px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.login-title {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-weight: 600;
}

.login-form {
  width: 100%;
  margin: 0 auto;
}

.login-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

:deep(.el-input__wrapper) {
  height: 40px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 验证码相关样式 */
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  padding: 5px 0;
  display: flex;
  width: auto;
  align-items: center;
  height: auto;
}

.captcha-image {
  width: 100%;
  height: 100%;
  cursor: pointer;
  border-radius: 4px;
  object-fit: contain;
  background-color: #f5f7fa;
  transition: all 0.2s;
}

.captcha-image:hover {
  opacity: 0.9;
}

.captcha-loading {
  opacity: 0.7;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23909399' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='12' y1='2' x2='12' y2='6'%3E%3C/line%3E%3Cline x1='12' y1='18' x2='12' y2='22'%3E%3C/line%3E%3Cline x1='4.93' y1='4.93' x2='7.76' y2='7.76'%3E%3C/line%3E%3Cline x1='16.24' y1='16.24' x2='19.07' y2='19.07'%3E%3C/line%3E%3Cline x1='2' y1='12' x2='6' y2='12'%3E%3C/line%3E%3Cline x1='18' y1='12' x2='22' y2='12'%3E%3C/line%3E%3Cline x1='4.93' y1='19.07' x2='7.76' y2='16.24'%3E%3C/line%3E%3Cline x1='16.24' y1='7.76' x2='19.07' y2='4.93'%3E%3C/line%3E%3C/svg%3E") center center no-repeat;
  background-size: 24px;
}
</style>
